<!-- <div id="jhpayform" style='border:none;position: relative;'><iframe id="jhpayformIframe" style='width:100%;border:none;height: 305px' src='https://hanpeng.oemsaas.cn/checkouts/payment/jhpaystripe/stripeForm?jhpay=1&store_id=26817&order_number=TD2023090428751&local_token=11b9891fd47d3ad9c609ae25a9a7739b&payment_id=16532'></iframe></div>
<script language="javascript">
$(function (){
    
    moi.appendLoading({theme: 'light',container:'#jhpayform'});
    var jhpayformIframe = document.getElementById('jhpayformIframe')
    function stripeCompleteCallback(){
        jhpayformIframe.contentWindow.postMessage({type:"jhpaystripe",code: 200},'*');
    }
     window.addEventListener('message',function(event){
        if(event.data && event.data.type && event.data.type =='jhpaystripe'){
            if(event.data.code == 200){
                return  moi.removeLoading("#jhpayform");
            }
            
            if(event.data.code == 300){
                  const paypalVerified = moi.onEvent("paypalVerified");
                    if(paypalVerified.results && paypalVerified.results.length){
                      paypalVerified.results[0].then(function(result){
                        if(!result){
                          jhpayformIframe.contentWindow.postMessage({type:"jhpaystripe",code: 400},'*');
                        }else{
                            stripeCompleteCallback()
                        }
                      })
                    }else{
                            stripeCompleteCallback()
                    }
            }
        }
    });
})
    
</script> -->

<div id="jhpayform" style='border:none;position: relative;'>
  <iframe id="jhpayformIframe" style='width:100%;border:none;height: 305px' src='https://hanpeng.oemsaas.cn/checkouts/payment/jhpaystripe/stripeForm?jhpay=1&store_id=26817&order_number=TD2023090428751&local_token=11b9891fd47d3ad9c609ae25a9a7739b&payment_id=16532'></iframe>
</div>
<script language="javascript">
  $(function () {
    $.paymentAPostMessage({
      form: "#jhpayform",
      iframe:"#jhpayformIframe",
    })
  })
</script>

<style>
  #stripe-element {
    margin-bottom: 14px;
    min-height: 100px;
  }
</style>

<div id="stripe-form" style="position: relative; width: 100%">
  <div id="stripe-element"></div>
  <div id="stripe-button"></div>
  <div id="payment-message"></div>
</div>

<script language="javascript">
  $(function () {
    let elements;
    let stripe;

    $.createPaymentCard({
      src: "https://js.stripe.com/v3/",
      button: "#stripe-button",
      form: "#stripe-form",
      async scriptSuccess({ disableButton, enabledButton }) {
        disableButton();
        stripe = Stripe("{$token_data['stripe_pub_key']}");
        // 检查链接是否包含payment_intent_client_secret 验证返回状态
        const clientSecret = new URLSearchParams(window.location.search).get(
          "payment_intent_client_secret"
        );
        if (clientSecret) {
          const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

          switch (paymentIntent.status) {
            case "succeeded":
              await fetch("{$saveOrder}&id=" + paymentIntent.id, {
                method: "GET"
              })
              $.toast({ container: "#payment-message", text: "Payment succeeded!" })
              parent.location.href = "{$successUrl}";
              break;
            case "processing":
              await fetch("{$saveOrder}&id=" + paymentIntent.id, {
                method: "GET"
              })
              $.toast({ container: "#payment-message", text: "Your payment is processing." })
              window.location.href = "{$pendingUrl}";
              break;
            case "requires_payment_method":
              $.toast({ container: "#payment-message", text: "Your payment was not successful, please try again." })
              break;
            default:
              $.toast({ container: "#payment-message", text: "Something went wrong." })
              break;
          }
          return;
        }

        const options = {
          paymentMethodTypes: ['card'],
          mode: 'payment',
          currency: '{$currency}',
          amount: $payamount,
        };
        
        elements = stripe.elements(options);
        const paymentElement = elements.create("payment", {
          fields: {
            billingDetails: {
              address: 'never'
            }
          }
        });
        paymentElement.mount("#stripe-element");
        paymentElement.on('ready', function (event) {
          enabledButton()
        });
        paymentElement.on('loaderror', function (event) {
          if (event.error) {
            $.toast({ container: "#payment-message", text: event.error.message })
          }
        });
      },
      async verified() {
        const { error: submitError } = await elements.submit();
        if (submitError) {
          return false;
        }
        return true

      },
      async submit({ showLoading, hideLoading }) {
        showLoading()
        const { clientSecret, msg } = await fetch("{$create}", {
          method: "POST",
          headers: { "Content-Type": "application/json" }
        }).then((r) => r.json())
        if (msg) {
          $.toast({ container: "#payment-message", text: msg })
          hideLoading();
          return
        }
        const { error } = await stripe.confirmPayment({
          elements,
          clientSecret,
          confirmParams: {
            return_url: "{$domain}/checkouts/payment/jhpaystripe/return?jhpay=1&checkout_token={$order->checkout_token}&order_number={$order->order_number}&payment_id={$paymentId}&store_id={$order->store_id}&local_token={$local_token}",
            payment_method_data: {
              billing_details: {
                address: {
                  "city": "{$billingAddress['city']}",
                  "country": "{$billingAddress['country_code']}",
                  "line1": "{$billingAddress['address1']}",
                  "line2": "{$billingAddress['address2']}",
                  "postal_code": "{$billingAddress['zip']}",
                  "state": "{$billingAddress['province_code']}"
                }
              }
            }
          },
        });

        if (error.type === "card_error" || error.type === "validation_error") {
          $.toast({ container: "#payment-message", text: error.message })
        }else {
          $.toast({ container: "#payment-message", text: "An unexpected error occured." })
        }
        hideLoading();
      }
    })
  })
</script>

<!-- <style>

  #card {
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }

  .card_btn {
    background: #ed3445;
    color: #fff;
    text-align: center;
    height: 40px;
    line-height: 40px;
    border: 0;
    width: 100%;
    border-radius: 5px;
    margin-top: 10px;
    font-size: 14px;
    cursor: pointer;
  }

  .error {
    visibility: hidden;
    text-align: center;
    margin-top: 10px;
    color: #ed3445;
    padding-left: 5px;
    padding-right: 5px
  }

  .error svg {
    vertical-align: middle;
  }

  .visible {
    visibility: visible;
  }

  @media screen and (max-width: 680px) {
    .example4 .container {
      padding: 10px 10px 0;
    }

    .InputContainer:after {
      margin-left: 30%;
    }
  }

  .hidden {
    display: none;
  }

  #payment-message {
    color: rgb(105, 115, 134);
    font-size: 16px;
    line-height: 20px;
    padding-top: 12px;
    text-align: center;
  }

  #payment-element {
    margin-bottom: 24px;
  }

  /* Buttons and links */
  button {
    background: #5469d4;
    font-family: Arial, sans-serif;
    color: #ffffff;
    border-radius: 4px;
    border: 0;
    padding: 12px 16px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    display: block;
    transition: all 0.2s ease;
    box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
    width: 100%;
  }

  button:hover {
    filter: contrast(115%);
  }

  button:disabled {
    opacity: 0.5;
    cursor: default;
  }

  /* spinner/processing state, errors */
  .spinner,
  .spinner:before,
  .spinner:after {
    border-radius: 50%;
  }

  .spinner {
    color: #ffffff;
    font-size: 22px;
    text-indent: -99999px;
    margin: 0px auto;
    position: relative;
    width: 20px;
    height: 20px;
    box-shadow: inset 0 0 0 2px;
    -webkit-transform: translateZ(0);
    -ms-transform: translateZ(0);
    transform: translateZ(0);
  }

  .spinner:before,
  .spinner:after {
    position: absolute;
    content: "";
  }

  .spinner:before {
    width: 10.4px;
    height: 20.4px;
    background: #5469d4;
    border-radius: 20.4px 0 0 20.4px;
    top: -0.2px;
    left: -0.2px;
    -webkit-transform-origin: 10.4px 10.2px;
    transform-origin: 10.4px 10.2px;
    -webkit-animation: loading 2s infinite ease 1.5s;
    animation: loading 2s infinite ease 1.5s;
  }

  .spinner:after {
    width: 10.4px;
    height: 10.2px;
    background: #5469d4;
    border-radius: 0 10.2px 10.2px 0;
    top: -0.1px;
    left: 10.2px;
    -webkit-transform-origin: 0px 10.2px;
    transform-origin: 0px 10.2px;
    -webkit-animation: loading 2s infinite ease;
    animation: loading 2s infinite ease;
  }

  @-webkit-keyframes loading {
    0% {
      -webkit-transform: rotate(0deg);
      transform: rotate(0deg);
    }

    100% {
      -webkit-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }

  @keyframes loading {
    0% {
      -webkit-transform: rotate(0deg);
      transform: rotate(0deg);
    }

    100% {
      -webkit-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }

  @media only screen and (max-width: 600px) {
    form {
      width: 80vw;
      min-width: initial;
    }
  }
</style> -->

<!-- <form id="payment-form" style="position: relative; width: 100%">
  <div id="payment-element">
  </div>
  <button id="submit" class="hidden">
    <div class="spinner hidden" id="spinner"></div>
    <span id="button-text">Pay</span>
  </button>
  <div id="payment-message" class="hidden"></div>
</form>
<div class=clear10></div>
<script src="https://js.stripe.com/v3/"></script> -->

<script language="javascript">
  // window.parent.postMessage({ type: "jhpaystripe", code: 200, data: "" }, '*');
  // // This is a public sample test API key.
  // // Don’t submit any personally identifiable information in requests made with this key.
  // // Sign in to see your own test API key embedded in code samples.
  // const stripe = Stripe("{$token_data['stripe_pub_key']}");
  // let elements;
  // initialize();
  // checkStatus();

  // document
  //   .querySelector("#payment-form")
  //   .addEventListener("submit", handleSubmit);

  // // Fetches a payment intent and captures the client secret
  // async function initialize() {
  //   setLoading(false);

  //   const options = {
  //     paymentMethodTypes: ['card'],
  //     mode: 'payment',
  //     currency: '{$currency}',
  //     amount: $payamount,
  //   };

  //   elements = stripe.elements(options);
  //   const paymentElement = elements.create("payment", {
  //     fields: {
  //       billingDetails: {
  //         address: 'never'
  //       }
  //     },

  //   });

  //   paymentElement.mount("#payment-element");

  //   paymentElement.on('ready', function (event) {


  //     document.querySelector("#submit").classList.remove("hidden");
  //   });
  // }


  // async function completeSubmit() {

  //   const { clientSecret, msg } = await fetch("{$create}", {
  //     method: "POST",
  //     headers: { "Content-Type": "application/json" }
  //   }).then((r) => r.json())
  //   if (msg) {
  //     showMessage(msg);
  //     setLoading(false);
  //     return
  //   }
  //   const { error } = await stripe.confirmPayment({
  //     elements,
  //     clientSecret,
  //     confirmParams: {
  //       // Make sure to change this to your payment completion page
  //       return_url: "{$domain}/checkouts/payment/jhpaystripe/return?jhpay=1&checkout_token={$order->checkout_token}&order_number={$order->order_number}&payment_id={$paymentId}&store_id={$order->store_id}&local_token={$local_token}",
  //       payment_method_data: {
  //         billing_details: {
  //           address: {
  //             "city": "{$billingAddress['city']}",
  //             "country": "{$billingAddress['country_code']}",
  //             "line1": "{$billingAddress['address1']}",
  //             "line2": "{$billingAddress['address2']}",
  //             "postal_code": "{$billingAddress['zip']}",
  //             "state": "{$billingAddress['province_code']}"
  //           }
  //         }
  //       }
  //     },
  //   });

  //   // This point will only be reached if there is an immediate error when
  //   // confirming the payment. Otherwise, your customer will be redirected to
  //   // your `return_url`. For some payment methods like iDEAL, your customer will
  //   // be redirected to an intermediate site first to authorize the payment, then
  //   // redirected to the `return_url`.
  //   if (error.type === "card_error" || error.type === "validation_error") {
  //     showMessage(error.message);
  //   } else {
  //     showMessage("An unexpected error occured.");
  //   }

  //   setLoading(false);
  // }

  // async function handleSubmit(e) {
  //   e.preventDefault();
  //   // Trigger form validation and wallet collection
  //   const { error: submitError } = await elements.submit();
  //   if (submitError) {
  //     return;
  //   }
  //   setLoading(true);
  //   window.parent.postMessage({ type: "jhpaystripe", code: 300, data: "" }, '*');
  // }

  // // Fetches the payment intent status after payment submission
  // async function checkStatus() {
  //   const clientSecret = new URLSearchParams(window.location.search).get(
  //     "payment_intent_client_secret"
  //   );

  //   if (!clientSecret) {
  //     return;
  //   }

  //   const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

  //   switch (paymentIntent.status) {
  //     case "succeeded":
  //       await fetch("{$interfaceCallback}&id=" + paymentIntent.id, {
  //         method: "GET"
  //       })
  //       showMessage("Payment succeeded!");
  //       window.location.href = "{$successUrl}";
  //       break;
  //     case "processing":
  //       await fetch("{$interfaceCallback}&id=" + paymentIntent.id, {
  //         method: "GET"
  //       })
  //       showMessage("Your payment is processing.");
  //       window.location.href = "{$pendingUrl}";
  //       break;
  //     case "requires_payment_method":
  //       showMessage("Your payment was not successful, please try again.");
  //       break;
  //     default:
  //       showMessage("Something went wrong.");
  //       break;
  //   }
  // }

  // // ------- UI helpers -------

  // function showMessage(messageText) {
  //   const messageContainer = document.querySelector("#payment-message");

  //   messageContainer.classList.remove("hidden");
  //   messageContainer.textContent = messageText;

  //   setTimeout(function () {
  //     messageContainer.classList.add("hidden");
  //     messageText.textContent = "";
  //   }, 4000);
  // }

  // // Show a spinner on payment submission
  // function setLoading(isLoading) {
  //   if (isLoading) {
  //     // Disable the button and show a spinner
  //     document.querySelector("#submit").disabled = true;
  //     document.querySelector("#spinner").classList.remove("hidden");
  //     document.querySelector("#button-text").classList.add("hidden");
  //   } else {
  //     document.querySelector("#submit").disabled = false;
  //     document.querySelector("#spinner").classList.add("hidden");
  //     document.querySelector("#button-text").classList.remove("hidden");
  //   }
  // }

  // window.addEventListener('message', function (event, s) {
  //   if (event.data && event.data.type && event.data.type == 'jhpaystripe') {
  //     if (event.data.code == 200) {
  //       completeSubmit()
  //       return
  //     }

  //     if (event.data.code == 400) {
  //       setLoading(false);
  //     }
  //   }
  // })
</script>

        <style>

/* Variables */

#card{padding:10px 15px;border:1px solid #ddd;border-radius:5px;}

.card_btn{background: #ed3445;color: #fff;text-align: center;height: 40px;line-height: 40px;border: 0;width: 100%;border-radius: 5px;margin-top: 10px;font-size: 14px;cursor: pointer;}

.error{visibility:hidden;text-align:center;margin-top:10px;color:#ed3445; padding-left:5px;padding-right:5px}

.error svg{vertical-align:middle;}

.visible{ visibility:visible;}

@media screen and (max-width: 680px){

.example4 .container{padding:10px 10px 0;}

.InputContainer:after{margin-left:30%;}

}

.hidden {

  display: none;

}



#payment-message {

  color: rgb(105, 115, 134);

  font-size: 16px;

  line-height: 20px;

  padding-top: 12px;

  text-align: center;

}



#payment-element {

  margin-bottom: 24px;

}



/* Buttons and links */

button {

  background: #5469d4;

  font-family: Arial, sans-serif;

  color: #ffffff;

  border-radius: 4px;

  border: 0;

  padding: 12px 16px;

  font-size: 16px;

  font-weight: 600;

  cursor: pointer;

  display: block;

  transition: all 0.2s ease;

  box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);

  width: 100%;

}

button:hover {

  filter: contrast(115%);

}

button:disabled {

  opacity: 0.5;

  cursor: default;

}



/* spinner/processing state, errors */

.spinner,

.spinner:before,

.spinner:after {

  border-radius: 50%;

}

.spinner {

  color: #ffffff;

  font-size: 22px;

  text-indent: -99999px;

  margin: 0px auto;

  position: relative;

  width: 20px;

  height: 20px;

  box-shadow: inset 0 0 0 2px;

  -webkit-transform: translateZ(0);

  -ms-transform: translateZ(0);

  transform: translateZ(0);

}

.spinner:before,

.spinner:after {

  position: absolute;

  content: "";

}

.spinner:before {

  width: 10.4px;

  height: 20.4px;

  background: #5469d4;

  border-radius: 20.4px 0 0 20.4px;

  top: -0.2px;

  left: -0.2px;

  -webkit-transform-origin: 10.4px 10.2px;

  transform-origin: 10.4px 10.2px;

  -webkit-animation: loading 2s infinite ease 1.5s;

  animation: loading 2s infinite ease 1.5s;

}

.spinner:after {

  width: 10.4px;

  height: 10.2px;

  background: #5469d4;

  border-radius: 0 10.2px 10.2px 0;

  top: -0.1px;

  left: 10.2px;

  -webkit-transform-origin: 0px 10.2px;

  transform-origin: 0px 10.2px;

  -webkit-animation: loading 2s infinite ease;

  animation: loading 2s infinite ease;

}



@-webkit-keyframes loading {

  0% {

    -webkit-transform: rotate(0deg);

    transform: rotate(0deg);

  }

  100% {

    -webkit-transform: rotate(360deg);

    transform: rotate(360deg);

  }

}

@keyframes loading {

  0% {

    -webkit-transform: rotate(0deg);

    transform: rotate(0deg);

  }

  100% {

    -webkit-transform: rotate(360deg);

    transform: rotate(360deg);

  }

}



@media only screen and (max-width: 600px) {

  form {

    width: 80vw;

    min-width: initial;

  }

}

</style>



    <!-- Display a payment form -->

    <form id="payment-form" style="position: relative; width: 100%">

      <div id="payment-element">

        <!--Stripe.js injects the Payment Element-->

      </div>

      <button id="submit"  class="hidden">

        <div class="spinner hidden" id="spinner"></div>

        <span id="button-text">Pay</span>

      </button>

      <div id="payment-message" class="hidden"></div>

    </form>

<div class=clear10></div>

<script src="https://js.stripe.com/v3/"></script>



<script language="javascript">

 window.parent.postMessage({type:"jhpaystripe",code:200,data:""},'*');

// This is a public sample test API key.

// Don’t submit any personally identifiable information in requests made with this key.

// Sign in to see your own test API key embedded in code samples.

const stripe = Stripe("{$token_data['stripe_pub_key']}");

let elements;

initialize();

checkStatus();



document

  .querySelector("#payment-form")

  .addEventListener("submit", handleSubmit);



// Fetches a payment intent and captures the client secret

async function initialize() {

  setLoading(false);

  

  const options = {

  paymentMethodTypes:['card'],

  mode: 'payment',

  currency: '{$currency}',

  amount: $payamount,

};



  elements = stripe.elements(options);

  const paymentElement = elements.create("payment",{ 

      fields: {

          billingDetails: {

            address: 'never'

          }

        },

        

  });

  

  paymentElement.mount("#payment-element");



  paymentElement.on('ready', function(event) {

      



      document.querySelector("#submit").classList.remove("hidden");

  }); 

}





async function completeSubmit(){

    

       const { clientSecret,msg } = await fetch("{$create}", {

    method: "POST",

    headers: { "Content-Type": "application/json" }

  }).then((r) => r.json())

  if(msg){

      showMessage(msg);

      setLoading(false);

      return 

  }

     const { error } = await stripe.confirmPayment({

    elements,

    clientSecret,

    confirmParams: {

// Make sure to change this to your payment completion page

         return_url: "{$domain}/checkouts/payment/jhpaystripe/return?jhpay=1&checkout_token={$order->checkout_token}&order_number={$order->order_number}&payment_id={$paymentId}&store_id={$order->store_id}&local_token={$local_token}",

         payment_method_data : {

            billing_details : {

               address : { 

                  "city": "{$billingAddress['city']}",

                  "country": "{$billingAddress['country_code']}",

                  "line1": "{$billingAddress['address1']}",

                  "line2": "{$billingAddress['address2']}",

                  "postal_code": "{$billingAddress['zip']}",

                  "state": "{$billingAddress['province_code']}"

               } 

           }

         }   

    },

  });



// This point will only be reached if there is an immediate error when 

// confirming the payment. Otherwise, your customer will be redirected to

// your `return_url`. For some payment methods like iDEAL, your customer will

// be redirected to an intermediate site first to authorize the payment, then

// redirected to the `return_url`.

  if (error.type === "card_error" || error.type === "validation_error") {

    showMessage(error.message);

  } else {

    showMessage("An unexpected error occured.");

  }



  setLoading(false);

}



async function handleSubmit(e) {

  e.preventDefault();

  // Trigger form validation and wallet collection

      const {error: submitError} = await elements.submit();

      if (submitError) {

        return;

      }

      setLoading(true);

  window.parent.postMessage({type:"jhpaystripe",code:300,data:""},'*');

}



// Fetches the payment intent status after payment submission

async function checkStatus() {

  const clientSecret = new URLSearchParams(window.location.search).get(

    "payment_intent_client_secret"

  );



  if (!clientSecret) {

    return;

  }



  const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);



  switch (paymentIntent.status) {

    case "succeeded":

      await fetch("{$saveOrder}&id="+paymentIntent.id, {

         method: "GET"

  })  

      showMessage("Payment succeeded!");

      window.location.href = "{$successUrl}";

      break;

    case "processing":

          await fetch("{$saveOrder}&id="+paymentIntent.id, {

         method: "GET"

  })  

      showMessage("Your payment is processing.");

          window.location.href = "{$pendingUrl}";

      break;

    case "requires_payment_method":

      showMessage("Your payment was not successful, please try again.");

      break;

    default:

      showMessage("Something went wrong.");

      break;

  }

}



// ------- UI helpers -------



function showMessage(messageText) {

  const messageContainer = document.querySelector("#payment-message");



  messageContainer.classList.remove("hidden");

  messageContainer.textContent = messageText;



  setTimeout(function () {

    messageContainer.classList.add("hidden");

    messageText.textContent = "";

  }, 4000);

}



// Show a spinner on payment submission

function setLoading(isLoading) {

  if (isLoading) {

    // Disable the button and show a spinner

    document.querySelector("#submit").disabled = true;

    document.querySelector("#spinner").classList.remove("hidden");

    document.querySelector("#button-text").classList.add("hidden");

  } else {

    document.querySelector("#submit").disabled = false;

    document.querySelector("#spinner").classList.add("hidden");

    document.querySelector("#button-text").classList.remove("hidden");

  }

}



   window.addEventListener('message',function(event, s){

        if(event.data && event.data.type && event.data.type =='jhpaystripe'){

            if(event.data.code == 200){

                completeSubmit()

                return

            }

            

            if(event.data.code == 400){

                setLoading(false);

            }

        }

    })

</script>
